package cn.uin.infrastructure.adapter.port;

import cn.uin.domain.auth.adapter.port.IAuthNotificationPort;
import cn.uin.domain.auth.model.entity.SendEmailEntity;
import cn.uin.infrastructure.redis.IRedisService;
import cn.uin.types.common.RedisConstants;
import cn.uin.types.common.TextConstants;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import cn.uin.types.utils.VerificationCodeUtils;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AuthNotificationPort
 * @Description:认证通知服务实现
 * @Author: Administrator
 * @CreateDate: 2025/10/27 15:29
 * @Version: 1.0
 */
@Slf4j
@Service
public class AuthNotificationPort implements IAuthNotificationPort {

	@Resource
	private JavaMailSender mailSender;

	@Resource
	private Client client;

	@Value("${sms.aliyun.otherInfos.register.sign-name}")
	private String register_sign_name;

	@Value("${sms.aliyun.otherInfos.register.template-code}")
	private String register_template_code;

	@Resource
	private IRedisService redisService;

	@Value("${spring.mail.username}")
	private String emailFrom;

	@Override
	public boolean sendEmailCode(Integer type, String email) {
		// TODO 后续调整为异步MQ处理
		String redisKey = type == 1 ? RedisConstants.EMAIL_REGISTER_CODE : RedisConstants.EMAIL_LOGIN_CODE;
		try {
			if (redisService.isExists(redisKey + email)) {
				throw new AppException(ResponseCode.C0001.getCode(), ResponseCode.C0001.getInfo());
			}
			// 生成验证码
			String code = VerificationCodeUtils.generateNumericCode();
			SimpleMailMessage message = new SimpleMailMessage();
			message.setTo(email);
			message.setSubject(TextConstants.AUTH_EMAIL_SUBJECT);
			message.setText(TextConstants.EMAIL_TEXT + code);
			message.setFrom(emailFrom);
			mailSender.send(message);

			//保存验证码到Redis
			redisService.setValue(redisKey + email, code, 1000 * 60 * 3);
			return true;
		} catch (Exception e) {
			log.error("发送邮件失败:{}", e.getMessage());
			return false;
		}
	}

	@Override
	public boolean sendPhoneCode(Integer type, String phone) {
		// TODO 后续调整为异步MQ处理
		String redisKey = type == 1 ? RedisConstants.PHONE_REGISTER_CODE : RedisConstants.PHONE_LOGIN_CODE;
		if (redisService.isExists(redisKey + phone)) {
			throw new AppException(ResponseCode.C0001.getCode(), ResponseCode.C0001.getInfo());
		}
		SendSmsRequest sendSmsRequest = new SendSmsRequest();
		sendSmsRequest.setPhoneNumbers(phone);
		sendSmsRequest.setSignName(register_sign_name);
		sendSmsRequest.setTemplateCode(register_template_code);

		// 生成验证码
		String code = VerificationCodeUtils.generateNumericCode();
		Map<String, Object> map = new HashMap<>();
		map.put("code", code);
		sendSmsRequest.setTemplateParam(JSONObject.toJSONString(map));
		try {
			SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
			SendSmsResponseBody body = sendSmsResponse.getBody();
			if (TextConstants.OK.equals(body.getCode())) {
				// 写入缓存
				redisService.setValue(redisKey + phone, code, 1000 * 60 * 3);
				return true;
			}
		} catch (Exception e) {
			log.error("发送短信错误:{}", e.getMessage());
			throw new AppException(ResponseCode.C0003.getCode(), ResponseCode.C0003.getInfo());
		}
		return false;
	}
}
